package com.newvpn.fastbest.zenith.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.newvpn.fastbest.zenith.VPNApp;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public final class LimitHelper {

    private static final Map<String, String> BLOCKS = new HashMap<String, String>() {{
        put("cu", "368");
        put("ir", "432");
         put("kp", "467");
        // put("sy", "417");
    }};

    public LimitHelper() {
        // Constructor is empty, moved initialization to static block
    }

    public boolean isLimit() {
        return isChinaBlocked() || isCountriesSanctionedByUSBlocked();
    }

    private boolean isChinaBlocked() {
        String simMcc = getSimMcc();
        String netMcc = getNetMcc();
        String country = getCountry();
        return "zh".equals(Locale.getDefault().getLanguage()) || (simMcc.startsWith("460") || netMcc.startsWith("460")) || "cn".equals(country);
    }

    private String getSimMcc() {
        return getMccFromOperator(getSimOperator());
    }

    private String getNetMcc() {
        return getMccFromOperator(getNetOperator());
    }

    private static String getMccFromOperator(String operator) {
        if (TextUtils.isEmpty(operator)) {
            return "";
        }
        return operator;
    }

    private boolean isCountriesSanctionedByUSBlocked() {
        String simMcc = getSimMcc();
        String netMcc = getNetMcc();
        String country = getCountry();
        return BLOCKS.values().stream().anyMatch(mcc -> simMcc.startsWith(mcc) || netMcc.startsWith(mcc))
                || BLOCKS.keySet().stream().anyMatch(country::equalsIgnoreCase);
    }

    private static String getSimOperator() {
        return getOperator((TelephonyManager)VPNApp.getBase().getSystemService(Context.TELEPHONY_SERVICE));
    }

    private static String getNetOperator() {
        return getOperator((TelephonyManager)VPNApp.getBase().getSystemService(Context.TELEPHONY_SERVICE));
    }

    private static String getOperator(TelephonyManager telephonyManager) {
        return telephonyManager != null ? telephonyManager.getSimOperator() : "";
    }

    public static String getCountry() {
        return Locale.getDefault().getCountry();
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
        return false;
    }
}